<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div />
        <div>
          <el-form-item>
            <el-button type="primary" @click="onVisible(1)">新增分类</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <el-table v-loading="listLoading" row-key="id" :row-class-name="tableRowClassName" :data="tidList" border
      :tree-props="{ children: 'children' }">
      <el-table-column align="center" width="60" />
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="picurl" label="分类图片" width="150" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.picurl" :preview-src-list="[scope.row.picurl]" />
        </template>
      </el-table-column>
      <el-table-column prop="tname" label="所属分区" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.pid == 0">{{ scope.row.tname }}</el-tag>
          <div v-else>{{ scope.row.tname }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="content" show-overflow-tooltip label="分类描述" align="center" />
      <el-table-column prop="positions" label="是否首页显示" width="150" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.positions == 0">是</el-tag>
          <el-tag v-if="scope.row.positions == 1" type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="150" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0"
            @change="(val) => { return SetValid(val, scope.row) }" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="onVisible(3, scope.row)">编辑
          </el-button>
          <el-button v-if="scope.row.pid == 0" size="mini" type="success"
            @click="onVisible(2, scope.row)">新增子分类</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增-->
    <el-dialog width="1000px" :close-on-click-modal="false"
      :title="visibleType == '1' ? '新增一级分类' : visibleType == '2' ? '新增二级分类' : '编辑'" :visible.sync="dialogVisible"
      :destroy-on-close="true" @close="handleClose">
      <el-form ref="forms" :rules="rulesModel" :model="form" label-width="100px">
        <div>
          <el-form-item label="封面" prop="picurl">
            <UploadImageList :isImageList="false" :existImage="picurl" @success="val => picurl = val"
              :isDisplay="dialogVisible" />
            <span style="font-size:12px;color:red;">建议: 一级分类尺寸508*160;二级分类尺寸100*100</span>
          </el-form-item>
        </div>
        <div v-if="visibleType == '2'" class="flex" style="display: flex;">
          <el-form-item label="一级分类" prop="pid">
            <el-select v-model="form.pid" placeholder="请选择" :disabled="form.pid == 0 && visibleType == '1'">
              <el-option :key="0" label="请选择所属分类" :value="0" />
              <el-option v-for="item in changeTypeList" :key="item.id" :label="item.tname" :value="item.id" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="分类名称" prop="tname" style="width: 900px;">
          <el-input v-model="form.tname" :rows="2" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="content" style="width: 900px;">
          <el-input v-model="form.content" :rows="2" placeholder="请输入分类描述" />
        </el-form-item>
        <template v-if="visibleType == '1' || visibleType == '3'">
          <template v-if="form.pid == 0 || form.pid == null">
            <el-form-item label="取消首页显示">
              <el-switch v-model="form.positions" active-value="1" inactive-value="0" />
            </el-form-item>
          </template>
        </template>
        <el-form-item label="启用/禁用" prop="state">
          <el-switch v-model="form.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onEdit(1)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogImg" width="30%">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "../../../utils/auth.js";
import { mapState } from "vuex";
import {
  getgoodstypepage,
  GoodstypeEdti,
  GoodstypeSetstate
} from "@/api/goods.js";
export default {
  name: "Name",
  data() {
    return {
      dialogImg: false,
      dialogImageUrl: "",
      picurl: "",
      form: {},

      changeTypeList: [], // 当前分类下的所有一级菜单
      tidList: [],
      authname: "",
      PidList: [], // 一级菜单
      PidList2: [], // 分区
      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      dialogVisible: false,
      dialogVisible1: false,
      visibleType: "",
      rulesModel: {
        picurl: [{ required: true, message: "请上传封面", trigger: "blur" }],
        tname: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        content: [{ required: true, message: "请输入分类描述", trigger: "blur" }],
      }
    };
  },
  computed: {
    emitPath() {
      return this.visibleType == "1";
    }
  },
  mounted() {
    this.getPid();
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (row.pid > 0) {
        return "warning-row";
      }
      return "";
    },
    // 新增分类前  查询所有分类
    async beforeChangeType(id) {
      const a = [];
      const { list } = await getgoodstypepage({
        PageIndex: 1,
        PageSize: 10000
      });
      // 一级菜单
      list.forEach(item => {
        if (item.pid == 0) {
          a.push(item);
        }
      });
      this.changeTypeList = a;
    },
    // 分组筛选
    group(arr, parentId, isChild = 1) {
      const tree = [];
      arr.map(item => {
        if (isChild == 1) {
          if (item.pid === parentId) {
            if (this.group(arr, item.id, isChild + 1).length > 0) {
              item.children = this.group(arr, item.id, isChild + 1);
            }
            tree.push(item);
          }
        }
        if (isChild == 2) {
          if (item.pid === parentId) {
            if (this.group(arr, item.id, isChild + 1).length > 0) {
              item.children = this.group(arr, item.id, isChild + 1);
            }
            tree.push(item);
          }
        }
      });
      return tree;
    },

    async getPid() {
      const { list } = await getgoodstypepage({
        PageIndex: 1,
        PageSize: 10000
      });
      this.tidList = this.group(list, 0);
    },
    // 状态
    async SetValid(val, item) {
      // console.log("val, item", val, item);
      const { success, msg } = await GoodstypeSetstate({
        tid: item.id,
        state: Number(val)
      });
      if (success) {
        this.getData();
      }
      this.$message({
        message: msg,
        type: success ? "success" : "error"
      });
    },
    onEdit() {
      this.form.picurl = this.picurl;
      const froms = this.$refs["forms"];
      froms.validate(async valid => {
        if (valid) {
          this.form.positions = this.form.positions || '0';
          const { success, msg } = await GoodstypeEdti(this.form);
          if (success) {
            this.dialogVisible = false;
            this.dialogVisible1 = false;
            this.getData();
            setTimeout(() => {
              this.getPid();
            }, 500);
          }
          this.$message({
            message: msg,
            type: success ? "success" : "error"
          });
        } else {
          return false;
        }
      });
    },
    // 关闭前
    handleClose() {
      this.picurl = "";
      this.$refs.forms.resetFields();
      this.$refs.forms.clearValidate();
    },
    setForm() {
      this.form = {
        id: 0, // 默认0
        pid: 0, // 上级ID
        tname: "", // 分类名称
        content: "", // 分类描述
        picurl: "", // 图片路径
        state: 1, // 0:禁用；1：启用
        positions: "0", // 是否取消首页显示；“0”：首页显示：“1”：取消首页显示
        wards: 0,
      }
    },
    // 打开前
    async onVisible(type, item = {}) {
      this.visibleType = type;
      this.setForm();
      if (type == 2) { // 新增子分类
        this.form.pid = item.id;
      } else if (type == 3) {
        this.form = { ...item };
      }

      this.picurl = this.form.picurl;
      // 获取所有分类
      await this.beforeChangeType(item.id);
      this.dialogVisible = true;
    },
    async getData(address) {
      this.listLoading = true;
      const { list, pageIndex, totalCount } = await getgoodstypepage({
        PageIndex: this.PageIndex,
        PageSize: 10
      });
      this.totalCount = totalCount;
      this.tableData = list;
      this.listLoading = false;
    }
  }
};
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}


.avatar-uploader .el-upload {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
</style>
